fans_moveAndWaitAttentionButton = function () {
    sleep(2000);
    try {
        var node;
        var times = 0;
        do {
            sleep(1500);
            times++;
            moveToScreenHeightHalf(screenHeight * 0.7);
            node = pkg("com.xingin.xhs")
                .clz("android.widget.TextView")
                .bounds(0, screenHeightHalf, screenWidth, screenHeight)
                .text("关注")
                .getOneNodeInfo(1000);
            if (times > 10) {
                toast("没有弹出“关注”框框");
                break;
            }
        } while (node === null);

        if (node !== null) {
            sleep(500);
            node.clickCenter();
        } else {
            logw("没有合适的时机点击关注");
            sleep(1500);
            return false;
        }
    } catch (e) {
        loge("add fans error {}", e);
        return false;
    }
};

fans_clickedAndMove = function (x, y) {
    sleep(1500);
    try {
        var click = true;
        logd("app version {}", appVersion[1]);
        if (appVersion[1] <= "26") {
            click = clickPoint(x, y);
        }
        // TODO 高版本会自动刷新页面 成为 已关注
        if (click) {
            sleep(1500);
            moveToScreenHeightHalf(y);
            sleep(1500);
        } else {
            // TODO
        }
    } catch (e) {
        loge("clicked and move error {}", e);
    }
};

fans_runAttentionCommand = function () {
    sleep(2500);
    try {
        var attention = pkg("com.xingin.xhs")
            .clz("android.widget.TextView")
            .text("关注")
            .bounds(screenWidthHalf, 0, screenWidth, screenHeight)
            .getOneNodeInfo(2000);

        if (attention !== null) {
            var bottom = attention.visibleBounds.bottom;
            var y = attention.visibleBounds.top +
                (attention.visibleBounds.bottom - attention.visibleBounds.top) / 2;
            var left = attention.visibleBounds.left +
                (attention.visibleBounds.right - attention.visibleBounds.left) / 2;
            if (clickPoint(screenWidthHalf, bottom)) {
                fans_moveAndWaitAttentionButton();

                back();

                fans_clickedAndMove(left, y);

                // loop again
                fans_runAttentionCommand();
            } else {
                // TODO fail and need to loop
            }
        } else {
            // back() 关注列表
            back();
        }
    } catch (e) {
        loge("run attention loop error {}", e);
    }
};

/**
 * 点击关注按钮
 *
 * @returns {boolean}
 */
fans_getAttentionButtonToClick = function () {
    sleep(1500);
    try {
        var node = pkg("com.xingin.xhs")
            .clz("android.widget.TextView")
            .text("获赞与收藏")
            .getOneNodeInfo("10000");

        if (node === null) { // TODO 不知道具体在哪个页面
            loge("非主页~");
            return false;
        }
        sleep(1500);
        var click = node.parent().siblings()[0].clickCenter();
        sleep(1000);
        if (click) {
            var none = pkg("com.xingin.xhs")
                .clz("android.widget.TextView")
                .textMatch("小红书号：")
                .getOneNodeInfo("1000");
            if (none !== null) {
                loge("可能不在别人的主页哦~");
                sleep(1000);
                back();
                sleep(1000);
                back();
                sleep(1000);
                return false;
            } else {
                logi("进入别人的关注列表啦~");
                return true;
            }
        } else {
            loge("非个人主页");
            back();
            sleep(1000);
            back()
            sleep(1000);
            return false;
        }
    } catch (e) {
        loge("get attention error fans {}", e);
        back();
        sleep(1000);
        back();
        sleep(1000);
        return false;
    }
};


/**
 * 点击进入个人主页
 *
 * @returns {boolean}
 */
fans_getRightNodeToClick = function () {
    sleep(1500);
    try {
        // 视频和图文的 尽量保持一起适配
        var node = pkg("com.xingin.xhs")
            .clz("android.widget.TextView")
            .textMatch("关注")
            .getOneNodeInfo(10000);
        if (node === null) { // 可能存在找不到 “主页” 的情况
            logw("不在详情页面");
            // TODO 回到主页，继续开始
            back();
            sleep(1000);
            return false;
        }
        // 需要兼容 视频和图文的
        var bottom = node.visibleBounds.bottom;
        var left = node.visibleBounds.left - 200;

        logd("position {} | {}", bottom, left);

        if (bottom !== undefined && bottom !== "") {
            if (clickPoint(left, bottom)) {
                sleep(1000);
                logi("进入别人主页成功！");
                return true;
            } else {
                // TODO 回到主页，继续开始
                back();
                sleep(1000);
                return false;
            }
        }
        // TODO 回到主页，继续开始
        back();
        sleep(1000);
        return false;
    } catch (e) {
        loge("get right button error {}", e);
        return false;
    }
};

/**
 * 默认点击第一个吧
 */
fans_randomClickDetail = function () {
    sleep(1500);
    try {
        if (clickPoint(screenWidth / 4, screenHeight / 2)) {
            logi("点击文章");
            return true;
        } else {
            return false;
        }
    } catch (e) {
        loge("random click error {}", e);
        return false;
    }
};

/**
 * 打开首页
 */
fans_openMainButton = function () {
    try {
        var node = pkg("com.xingin.xhs")
            .clz("android.widget.TextView")
            .text("首页")
            .getOneNodeInfo("3000");
        if (node === null) {
            loge("不在小红书首页");
            return false;
        }
        var click = node.clickCenter();
        if (click) {
            sleep(3000);
            logd("打开首页成功");
            return true;
        } else {
            loge("打开首页失败");
            return false;
        }
    } catch (e) {
        loge("open main error {}", e);
        return false;
    }
};

/**
 * 所有的异常情况都需要内部回退 主页中
 */
fans_addFans = function () {
    while (true) {
        sleep(1500);

        // TODO 使用下拉刷新的方式进行刷新页面
        fans_refreshPage();
        sleep(3500);
        // 点击其中的一篇文章
        if (!fans_randomClickDetail()) {
            continue;
        }

        // 通过 ”关注“ 点击 进入到个人主页中
        if (!fans_getRightNodeToClick()) {
            continue;
        }

        // 存在点击失败的
        if (!fans_getAttentionButtonToClick()) {
            continue;
        }

        fans_runAttentionCommand();
    }
};

/**
 * 部分机型识别不了底部的按钮
 * 所以 只能通过下拉刷新来解决
 */
fans_refreshPage = function () {
    var touch1 = [];
    // 按下的初始坐标
    touch1.push({
        "action": 0,
        "x": device.getScreenWidth() / 2 + 100,
        "y": device.getScreenHeight() * 0.3,
        "pointer": 1,
        "delay": 200
    });
    // 手指弹起的坐标，也就是最终的坐标
    touch1.push({
        "action": 1,
        "x": device.getScreenWidth() / 2 + 100,
        "y": device.getScreenHeight() * 0.6,
        "pointer": 1,
        "delay": 200
    });
    // 移动的坐标
    touch1.push({
        "action": 2,
        "x": device.getScreenWidth() / 2 + 100,
        "y": device.getScreenHeight() * 0.6,
        "pointer": 1,
        "delay": 200
    });
    multiTouch(touch1, null, null, 1000);
};

/**
 * 部分手机不支持底部的读取 TODO
 */
fans_removeFans = function () {
    sleep(1500);
    while (true) {

        var judge = pkg("com.xingin.xhs")
            .clz("android.widget.EditText")
            .text("搜索已关注的人").getOneNodeInfo(1200);

        if (judge == null) {
            loge("不在自己的关注列表");
            exit();
        }

        addNodeFlag(0);
        var hasNode = pkg("com.xingin.xhs")
            .clz("android.widget.TextView")
            .text("已关注").getNodeInfo(1200);
        removeNodeFlag(0);
        if (hasNode != null) {
            for (var i = 0; i < hasNode.length; i++) {
                sleep(1500);
                var left = hasNode[i].visibleBounds.left;
                var right = hasNode[i].visibleBounds.right;
                var top = hasNode[i].visibleBounds.top;
                var bottom = hasNode[i].visibleBounds.bottom;

                var x = left + (right - left) / 2;
                var y = top + (bottom - bottom) / 2;
                logd("x {} | y {}", x, y);
                clickPoint(x, y);

                sleep(1000);
                pkg("com.xingin.xhs")
                    .clz("android.widget.Button")
                    .text("确定")
                    .getOneNodeInfo("2000").clickCenter();
            }
        }
        addNodeFlag(0);
        var hasNodeEach = pkg("com.xingin.xhs")
            .clz("android.widget.TextView")
            .text("互相关注").getNodeInfo(1200);
        removeNodeFlag(0);
        if (hasNodeEach != null) {
            for (var j = 0; j < hasNodeEach.length; j++) {
                sleep(1000);
                hasNodeEach[j].clickCenter();

                sleep(1000);
                pkg("com.xingin.xhs")
                    .clz("android.widget.Button")
                    .text("确定")
                    .getOneNodeInfo("2000").clickCenter();
            }
        }

        addNodeFlag(0);
        // 开始向下滑动
        var flag = pkg("com.xingin.xhs")
            .clz("androidx.recyclerview.widget.RecyclerView")
            .depth(13)
            .getOneNodeInfo(2000)
            .scrollForward();
        removeNodeFlag(0);

        sleep(2000);

        if (!flag) {
            sleep(1000);
            logi("尝试第二次滑动");
            flag = pkg("com.xingin.xhs")
                .clz("androidx.recyclerview.widget.RecyclerView")
                .depth(13)
                .getOneNodeInfo(2000)
                .scrollForward();
            if (!flag) {
                logi("滑不动啦~");
                break;
            }
        }
    }

    logi("拜了个拜ヾ(•ω•`)o");
    exit();
}
;

addFans_config = function () {
    isAddMoreFans = readConfigBoolean("isAddMoreFans");
    isIdMode = readConfigBoolean("idIdMode");
    isSelfMode = readConfigBoolean("isSelfMode");
    fans_ID = readConfigString("fans_id");
    FAN_ID_WAIT_TIME = readConfigInt("fan_id_wait_time");
    FAN_ID_WAIT_TIME_SELF = readConfigInt("fan_id_wait_time_self");
    logi("当前模式：{}", isAddMoreFans ? "上粉模式" : "取关模式");
    if (isAddMoreFans) {
        logi("模式选择：{}", isIdMode ? "精准账号关注" : "随机选取关注");
        logi("账号ID：{}", fans_ID);
        logi("自己选取关注：{}", isSelfMode);
        if (isSelfMode) {
            logi("不出现关注弹框等待时间：{}秒", FAN_ID_WAIT_TIME_SELF);
        } else {
            logi("不出现关注弹框等待时间：{}秒", FAN_ID_WAIT_TIME);
        }
    }
};

addFans_compare = function (a, b) {
    var top1 = a.visibleBounds.top;
    var top2 = b.visibleBounds.top;
    return top1 < top2 ? -1 : 1;
};

var fans_HasAdd = [];
addFans_addFansByID = function () {
    var mainFlag = true;
    while (mainFlag) {
        addNodeFlag(0);
        var toDoNodes = pkg("com.xingin.xhs")
            .clz("android.widget.TextView")
            .text("关注")
            .getNodeInfo(2000);
        if (toDoNodes != null) {
            // 进行排序的
            toDoNodes.sort(addFans_compare);

            for (var i = 0; i < toDoNodes.length; i++) {
                var single = toDoNodes[i];
                // 跳过左上角的关注
                if (single.visibleBounds.left < screenWidthHalf) {
                    continue;
                }

                // 保证index=0的时候，也能够忽略
                if (i === 0 &&
                    fans_HasAdd.indexOf(toDoNodes[i].nid) !== -1) {
                    logd("same");
                    continue;
                }

                // 只需要保留最后一个人的NID
                if (i === toDoNodes.length - 1) {
                    fans_HasAdd.push(toDoNodes[i].nid);
                } else {
                    fans_HasAdd = [];
                }

                var top = single.visibleBounds.top;
                var bottom = single.visibleBounds.bottom;
                var left = single.visibleBounds.left;
                var right = single.visibleBounds.right;
                var x = left + (right - left) / 2;
                var y = top + (bottom - top) / 2;
                clickPoint(360, y);

                sleep(1000);
                toast("个人主页啊~");

                var badNode = pkg("com.xingin.xhs")
                    .clz("android.widget.TextView")
                    .textMatch("因相关投诉该账户违反")
                    .getOneNodeInfo(800);

                if (badNode != null) {
                    toast("该账号违规啦，继续下一个啦~~");
                    sleep(1000);
                    back();
                    sleep(1000);
                    continue;
                }

                var scrollNode = pkg("com.xingin.xhs")
                    .clz("androidx.recyclerview.widget.RecyclerView")
                    .depth(15)
                    .getOneNodeInfo(2000);
                if (scrollNode != null) {
                    var times = 4;
                    var flag = false;
                    while (scrollNode.scrollForward()) {
                        times--;
                        sleep(1200);
                        // 等待关注的浮窗出现
                        var node = pkg("com.xingin.xhs")
                            .clz("android.widget.TextView")
                            .bounds(0, screenHeightHalf, screenWidth, screenHeight)
                            .text("关注")
                            .getOneNodeInfo(1000);
                        if (node != null) {
                            node.clickCenter();
                            toast("已经关注啦！！！！！");
                            flag = true;
                            break;
                        }
                        // 如果一直没有出现
                        if (times <= 0) {
                            toast("没有出现弹框~");
                            break;
                        }
                    }
                    // 没有点击的情况
                    if (!flag && times > 0) {
                        toast("滑不动了，估计文章太少了");
                        if (FAN_ID_WAIT_TIME > 0 || FAN_ID_WAIT_TIME_SELF > 0) {
                            if (isSelfMode) {
                                toast("休息" + FAN_ID_WAIT_TIME_SELF + "秒，在进行关注");
                                sleep(FAN_ID_WAIT_TIME_SELF * 1000);
                            } else {
                                toast("休息" + FAN_ID_WAIT_TIME + "秒，在进行关注");
                                sleep(FAN_ID_WAIT_TIME * 1000);
                            }
                        }
                    }

                    sleep(1400);
                    back();
                    sleep(1400);
                    if (!flag) {
                        // 在外面统一点击关注
                        clickPoint(x, y);
                        toast("没有出现弹框，只能在这里关注啦~~~");
                        sleep(1500);
                    }
                }
            }
        }

        sleep(500);
        mainFlag = pkg("com.xingin.xhs")
            .clz("androidx.recyclerview.widget.RecyclerView")
            .depth(13)
            .getOneNodeInfo(2000)
            .scrollForward();
        sleep(1500);
    }

    logi("没有啦~");
    logi("ヾ(•ω•`)o");
    exit();
};

fans_addFanByID = function () {
    if (fans_ID === "") {
        loge("账号ID为空");
        exit();
    }

    // 借用 multi 的部分逻辑
    if (multi_getSearchButtonByMainButton()) {
        if (multi_nextCarCommands(fans_ID)) {
            addFans_addFansByID();
        } else {
            loge("未知错误！！");
            exit();
        }
    } else {
        loge("上粉失败了...");
        exit();
    }

};

/**
 * 主函数
 */
var isIdMode = true;
var fans_ID = "";
var FAN_ID_WAIT_TIME = 0;
var FAN_ID_WAIT_TIME_SELF = 0;
var isSelfMode = false;
addFans = function () {
    addFans_config();

    if (isAddMoreFans) {
        logi("上粉模式开启");
        if (isSelfMode) {
            addFans_addFansByID();
        } else {
            if (isIdMode) {
                fans_addFanByID();
            } else {
                fans_addFans();
            }
        }
    } else {
        logi("取关模式开启");
        fans_removeFans();
    }
};
